import {PageContainer, ProDescriptions} from '@ant-design/pro-components';
import {Button, Card, Col, Form, Input, message, Row} from 'antd';
import React, {useEffect, useRef, useState} from 'react';
import {
    getInterfaceInfoByIdUsingGet,
    invokeInterfaceInfoUsingPost,
} from '@/services/api-share-backhend/interfaceInfoController';
import {useParams} from 'react-router';
import GetDebugTable from '@/pages/ShowList/DetailMes/component/GetDebugTable';
import {requestConfig} from '@/requestConfig';
import {StarTwoTone} from '@ant-design/icons';
import {
    addInterfaceCollectInfoUsingPost,
    deleteInterfaceCollectInfoUsingDelete,
} from '@/services/api-share-backhend/interfaceCollectInfoController';
import {history} from "@umijs/max";

const Index: React.FC = () => {
    const [data, setData] = useState<API.InterfaceInfo>();
    const [show, setShow] = useState<string>();
    const [loading, setLoading] = useState<boolean>();
    const [collected, setCollected] = useState<boolean>();
    const [invokeBtnDisable, setInvokeBtnDisable] = useState(() => false);

    const params = useParams();
    const formRef = useRef(null);
    const loadData = async () => {
        try {
            setLoading(true);
            // console.log('param', params);
            const res = await getInterfaceInfoByIdUsingGet({
                id: Number(params.id),
            });
            setLoading(false);
            setData(res.data);
            setCollected(res.data.collected)
            if (res.data.status === 0) {
                setInvokeBtnDisable(true);
            } else {
                setInvokeBtnDisable(false);
            }
            console.log(res.data);
        } catch (e) {
            setInvokeBtnDisable(true);
            setLoading(false);
            message.error(e.message);
        }
    };

    const onFinish = async (value) => {
        try {
            const postBody = JSON.parse(value.postRequestParam);
            console.log(postBody);
            const res: API.BaseResponseobject = await invokeInterfaceInfoUsingPost({
                id: data?.id,
                postRequestParam: postBody,
            });
            if (res?.data === null) {
                message.error(res.message);
            } else {
                // console.log(res.data);
                setShow(res?.data);
            }
        } catch (e: any) {
            message.error(e.message);
        }
    };

    const handleDownLoad = () => {
        // SDK 文件的 URL
        const sdkUrl = `${requestConfig.baseURL}/api/sdk.zip`; // 替换为你的 SDK 文件的实际 URL

        // 创建一个隐藏的链接元素
        const link = document.createElement('a');
        link.href = sdkUrl;
        link.download = `sdk.zip'`; // 设置下载的文件名

        // 触发点击事件以下载文件
        document.body.appendChild(link);
        link.click();

        // 移除链接元素
        document.body.removeChild(link);
    };

    const handleCollect = async (value) => {
        try {
            const res: API.BaseResponsePageInterfaceInfo = await addInterfaceCollectInfoUsingPost({
                interfaceId: value,
            });
            if (res.data != undefined && res.data != null) {
                setCollected(true)
            } else {
                message.error(res.message);
            }
        } catch (e) {
            message.error(e.message);
        }
    };

    const handleCollectRemove = async (value) => {
        try {
            const res: API.BaseResponsePageInterfaceInfo = await deleteInterfaceCollectInfoUsingDelete({
                interfaceId: value,
            });
            if (res.data != undefined && res.data != null) {
                setCollected(false)
            } else {
                history.push("/404")
                message.error(res.message);
            }
        } catch (e) {
            history.push("/404")
            message.error(e.message);
        }
    };
    const updateShow = (data) => {
        setShow(data);
    };
    useEffect(() => {
        loadData();
    }, []);

    const handleDebugClick = () => {
        if (formRef.current) {
            // @ts-ignore
            formRef.current.submit();
        }
    };

    if (loading === false) {
        return (
            <PageContainer>
                <Card
                    title={`接口名： ${data?.name}`}
                    extra={
                        <div style={{ display: 'flex', alignItems: 'center' }}>
                            {collected==true ? (
                                <div
                                    key="collect"
                                    style={{ fontSize: '15px', display: 'flex', alignItems: 'center' }}
                                    title={'点击取消收藏'}
                                    onClick={() => handleCollectRemove(data.id)}
                                >
                                    <StarTwoTone twoToneColor={'red'} style={{ fontSize: '18px' }} />   <a style={{ marginLeft: 3 }}>已收藏</a>
                                </div>
                            ) : (
                                <div
                                    key="collect"
                                    style={{ fontSize: '15px', display: 'flex', alignItems: 'center' }}
                                    title={'点击收藏'}
                                    onClick={() => handleCollect(data.id)}
                                >
                                    <StarTwoTone style={{ fontSize: '18px' }} />
                                    <a style={{ marginLeft: 3 }}>收藏</a>
                                </div>
                            )}
                            <Button
                                type="primary"
                                onClick={handleDownLoad}
                                style={{ marginLeft: 10 }}
                            >
                                下载SDK
                            </Button>
                        </div>
                    }
                >
                    <Row gutter={16}>
                        <Col span={8}>
                            <Card type="inner" title="接口状态">
                                {data?.status === 0 ? '已上线' : '已关闭'}
                            </Card>
                        </Col>
                        <Col span={8}>
                            <Card style={{marginTop: 2}} type="inner" title="接口地址">
                                {data?.url}
                            </Card>
                        </Col>
                        <Col span={8}>
                            <Card style={{marginTop: 2}} type="inner" title="请求方式">
                                {data?.method}
                            </Card>
                        </Col>

                        <Col span={8}>
                            <Card style={{marginTop: 2}} type="inner" title="请求头">
                                {data?.requestHeader}
                            </Card>
                        </Col>
                        <Col span={8}>
                            <Card style={{marginTop: 2}} type="inner" title="接口参数">
                                {data?.requestParams}
                            </Card>
                        </Col>
                        <Col span={8}>
                            <Card style={{marginTop: 2}} type="inner" title="响应头">
                                {data?.responseHeader}
                            </Card>
                        </Col>
                        <Col span={8}>
                            <Card type="inner" style={{marginTop: 2}} title="接口描述">
                                {data?.description}
                            </Card>
                        </Col>
                        <Col span={8}>
                            <Card style={{marginTop: 2}} type="inner" title="创建时间">
                                {new Date(data?.createTime).toLocaleString()}
                            </Card>
                        </Col>
                        <Col span={8}>
                            <Card style={{marginTop: 2}} type="inner" title="更新时间">
                                {new Date(data?.updateTime).toLocaleString()}
                            </Card>
                        </Col>
                    </Row>
                </Card>
                {data?.method === 'POST' || data?.method === 'PUT' ? (
                    <Card title="调试" style={{marginTop: '10px'}}>
                        <Row>
                            <Col span={12}>
                                <Card
                                    title={'请求参数'}
                                    extra={[
                                        <Button
                                            type={'primary'}
                                            onClick={handleDebugClick}
                                            htmlType={'submit'}
                                            disabled={invokeBtnDisable}
                                        >
                                            调试
                                        </Button>,
                                    ]}
                                >
                                    <Form
                                        name="basic"
                                        labelCol={{span: 12}}
                                        initialValues={{remember: true}}
                                        onFinish={onFinish}
                                        autoComplete="off"
                                        ref={formRef}
                                    >
                                        <Form.Item name={'postRequestParam'}>
                                            <Input.TextArea autoSize={{maxRows: 8}} defaultValue={'{\n\n}'}/>
                                        </Form.Item>
                                    </Form>
                                </Card>
                            </Col>
                            <Col span={12}>
                                <Card title={'请求返回值'}>
                                    <ProDescriptions style={{height: '155px'}}>
                                        <ProDescriptions.Item valueType="jsonCode">{show}</ProDescriptions.Item>
                                    </ProDescriptions>
                                </Card>
                            </Col>
                        </Row>
                    </Card>
                ) : (
                    <Card title={'在线调试'}>
                        {' '}
                        <Row>
                            <Col span={12}>
                                <GetDebugTable
                                    id={data?.id}
                                    requestParams={data?.requestParams}
                                    updateShow={updateShow}
                                    invokeBtnDisable={invokeBtnDisable}
                                >
                                    {' '}
                                </GetDebugTable>
                            </Col>
                            <Col span={12}>
                                <Card title={'请求返回值'}>
                                    {/*<div style={{ height: '155px' }}>{show}</div>*/}
                                    <ProDescriptions style={{height: '155px'}}>
                                        <ProDescriptions.Item valueType="jsonCode">{show}</ProDescriptions.Item>
                                    </ProDescriptions>
                                </Card>
                            </Col>{' '}
                        </Row>
                    </Card>
                )}
            </PageContainer>
        );
    }
};

export default Index;
